package pwd.allen.service;

import com.alibaba.fastjson.JSON;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.*;

public interface BaseService {

    /**
     * 打印线程信息
     * @param action all表示打印全部线程信息，否则只打印基本信息
     * @param id 根据threadId查询
     * @param excludes 根据threadName排除
     * @param includes 根据threadName包含
     * @return
     */
    default Object getThread(String action, Long id, String excludes, String includes, Integer top) {

        // 获取java线程管理器MXBean
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        List<ThreadInfo> threadInfoList = new ArrayList<ThreadInfo>();

        if (id != null) {
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(id);
            if (threadInfo != null) {
                threadInfoList.add(threadInfo);
            }
        } else {
            //  lockedMonitors参数表示是否获取同步的monitor信息，lockedSynchronizers表示是否获取同步的synchronizer
            ThreadInfo[] infos = threadMXBean.dumpAllThreads(false,false);

            if (includes != null) {
                for (ThreadInfo info : infos) {
                    boolean ifInclude = false;
                    for (String include : includes.split(",")) {
                        if (info.getThreadName().startsWith(include)) {
                            ifInclude = true;
                            break;
                        }
                    }
                    if (ifInclude) {
                        threadInfoList.add(info);
                    }
                }
            } else if (excludes != null) {
                for (ThreadInfo info : infos) {
                    boolean ifExclude = false;
                    for (String exclude : excludes.split(",")) {
                        if (info.getThreadName().startsWith(exclude)) {
                            ifExclude = true;
                            break;
                        }
                    }
                    if (ifExclude) {
                        continue;
                    }
                    threadInfoList.add(info);
                }
            } else {
                threadInfoList.addAll(Arrays.asList(infos));
            }
        }

        if (top != null && top < threadInfoList.size()) {
            threadInfoList = threadInfoList.subList(0, top);
        }

        if ("all".equals(action)) {
            return JSON.toJSON(threadInfoList);
        }
        List<Map> list = new ArrayList<Map>();
        for (ThreadInfo info : threadInfoList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("threadId", info.getThreadId());
            map.put("threadName", info.getThreadName());
            map.put("lockName", info.getLockName());
            list.add(map);
        }
        return JSON.toJSON(list);
    }
}
